﻿@inject IHttpService _httpService
@inject NavigationManager NavigationManager
@inject IDataCacheService _dataCacheService
@inject IEventService _eventService
@inject IPopupService PopupService

<MDialog @bind-Value="Dialog" Persistent
         MaxWidth="550">
    <MDCard>
        <MCardTitle Class="text-h5">
            编辑游玩记录
        </MCardTitle>
        <MCardText Class="pb-2">
            你可以在这里记录游玩状态和评分，还可以在个人空间中绑定Steam库存
        </MCardText>

        <MCardText>
            @if (isReady)
            {
                <MButtonGroup Tile Group Value="(int)Model.Type" ValueChanged="ValueChanged" Class="pb-2" Style=" display: flex; flex-wrap: wrap;" Color="primary">
                    <MButton Class="m-0" Value="(int)PlayedGameType.WantToPlay">
                        想玩
                    </MButton>
                    <MButton Class="m-0" Value="(int)PlayedGameType.Playing">
                        正在玩
                    </MButton>
                    <MButton Class="m-0" Value="(int)PlayedGameType.Played">
                        已玩
                    </MButton>
                    <MButton Class="m-0" Value="(int)PlayedGameType.Uninterested">
                        不感兴趣
                    </MButton>
                    <MButton Class="m-0" Value="(int)PlayedGameType.UnPlayed">
                        未玩
                    </MButton>
                </MButtonGroup>
                <CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaRating @bind-Value="Model.MusicSocre" Label="音乐" />
                <CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaRating @bind-Value="Model.PaintSocre" Label="美术" />
                <CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaRating @bind-Value="Model.ScriptSocre" Label="剧本" />
                <CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaRating @bind-Value="Model.ShowSocre" Label="演出" />
                <CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaRating @bind-Value="Model.SystemSocre" Label="程序" />
                @if (isDubbing)
                {
                    <CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaRating @bind-Value="Model.CVSocre" Label="配音" />

                }
                <CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaRating @bind-Value="Model.TotalSocre" Label="总评" />

                <MTextarea Label="@(Model.LoadSteamReview?"评语（已加载关联Steam账号数据）":"评语")" Rows="5" Placeholder="@($"超过{ToolHelper.MinValidPlayImpressionsLength}字才会被年度游戏评选收录哦~")"
                           @bind-Value="Model.PlayImpressions" Counter="true" >

                </MTextarea>
                <div class="row">
                    <div class="col-12 col-md-6">
                        <MCheckbox @bind-Value="Model.ShowPublicly"
                                   Label="公开（参与评选）" Class="m-0"
                                   HideDetails="true"></MCheckbox>
                    </div>
                    <div class="col-12 col-md-6">
                        <MCheckbox @bind-Value="Model.IsHidden"
                                   Label="不展示在个人主页中" Class="m-0"
                                   HideDetails="true"></MCheckbox>
                    </div>
                </div>
            }
            else
            {
                <CnGalWebSite.Components.Progressings.ProgressingCard Style="min-height:200px;" Class="mt-8" />

            }
        </MCardText>

        <MCardActions Class="pa-6 pt-0">
            <CnGalWebSite.Components.Buttons.MasaButton TextStyle OnClick="()=>Dialog=false" Icon="@IconType.Close.ToIconString()" Text="取消"/>
            <MSpacer></MSpacer>
            <CnGalWebSite.Components.Buttons.MasaButton Rounded OnClick="OnSubmit" Icon="@IconType.Save.ToIconString()" Text="保存" />
        </MCardActions>
    </MDCard>
</MDialog>
<CnGalWebSite.Components.Verifications.DeviceIdentification @ref="deviceIdentification" />

@code {

    [Parameter]
    public EventCallback OnChanged { get; set; }

    public int Id { get; set; }

    public GameRecordViewModel ViewModel { get; set; }

    public EditGameRecordModel Model = new EditGameRecordModel();

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }
    bool Dialog { get; set; }

    bool isReady = false;
    bool isDubbing;

    CnGalWebSite.Components.Verifications.DeviceIdentification deviceIdentification;


    public void ValueChanged(StringNumber index)
    {
        if (index != null)
        {
            Model.Type = (PlayedGameType)index.ToInt32();
        }
    }

    protected async Task OnInit()
    {
        try
        {
            Model = await _httpService.GetAsync<EditGameRecordModel>("api/playedgame/EditGameRecord/" + Id);
            isReady = true;
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "获取游玩记录失败");
        }
    }

    private async Task OnSubmit()
    {
        try
        {
            if (isDubbing == false)
            {
                Model.CVSocre = -1;
            }
            if (Model.ScriptSocre == 0 || Model.MusicSocre == 0 || Model.PaintSocre == 0 || Model.ShowSocre == 0 || Model.TotalSocre == 0 || Model.SystemSocre == 0 || Model.CVSocre == 0)
            {
                if (Model.ScriptSocre + Model.MusicSocre + Model.PaintSocre + Model.ShowSocre + Model.TotalSocre + Model.SystemSocre + Model.CVSocre != 0)
                {
                    await PopupService.EnqueueSnackbarAsync(new SnackbarOptions
                        {
                            Type = AlertTypes.Error,
                            Title = "请填写所有项目的评分",
                            Timeout = 4000
                        });
                    return;
                }
            }
            else
            {

                if (string.IsNullOrWhiteSpace(Model.PlayImpressions) || Model.PlayImpressions.Length <= ToolHelper.MinValidPlayImpressionsLength)
                {
                    if (_dataCacheService.ThemeSetting.PlayedGameInforCount >= 0)
                    {

                        await PopupService.EnqueueSnackbarAsync(new SnackbarOptions
                            {
                                Type = AlertTypes.Info,
                                Title = "提示",
                                Content = $"只有大于{ToolHelper.MinValidPlayImpressionsLength}字评语的评分才会记录到总分中哦。当然，不写评语也是OK的。" + (_dataCacheService.ThemeSetting.PlayedGameInforCount > 0 ? $"这个提醒还会再出现{_dataCacheService.ThemeSetting.PlayedGameInforCount}次。" : ""),
                                Timeout = 100000
                            });

                        _dataCacheService.ThemeSetting.PlayedGameInforCount--;
                        _eventService.OnSavaTheme();

                    }
                }
            }

            //获取身份失败信息
            if (deviceIdentification != null)
            {
                Model.Identification = await deviceIdentification.GetDeviceIdentificationModel();
            }


            var obj = await _httpService.PostAsync<EditGameRecordModel, Result>("api/playedgame/EditGameRecord", Model);
            //判断结果
            if (obj.Successful == false)
            {
                await PopupService.EnqueueSnackbarAsync(new SnackbarOptions
                    {
                        Type = AlertTypes.Error,
                        Title = obj.Error ?? "编辑游玩记录失败~",
                        Timeout = 4000
                    });
            }
            else
            {
                if (ViewModel != null)
                {
                    ViewModel.Type = Model.Type;
                    ViewModel.PlayImpressions = Model.PlayImpressions;
                    ViewModel.IsHidden = Model.IsHidden;
                    ViewModel.ShowPublicly = Model.IsHidden;
                    ViewModel.MusicSocre = Model.MusicSocre;
                    ViewModel.PaintSocre = Model.PaintSocre;
                    ViewModel.ScriptSocre = Model.ScriptSocre;
                    ViewModel.ShowSocre = Model.ShowSocre;
                    ViewModel.TotalSocre = Model.TotalSocre;
                }
                Dialog = false;
                await OnChanged.InvokeAsync();
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "编辑游玩记录失败");
        }
    }

    public async Task Refresh(bool dialog, int id, GameRecordViewModel viewModel, bool _isDubbing = true)
    {
        Dialog = dialog;
        Id = id;
        ViewModel = viewModel;
        isDubbing = _isDubbing;
        if (viewModel != null)
        {
            isDubbing = viewModel.IsDubbing;
        }

        await OnInit();

        StateHasChanged();
    }
}
